package com.ruoyi.web.controller.wechat;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.wechat.WechatConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.wechat.WechatTask;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.system.domain.wechat.request.vo.CreateForWechatTaskVO;
import com.ruoyi.system.domain.wechat.request.vo.FilterForWechatTaskListVO;
import com.ruoyi.system.service.wechat.IWechatTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信小程序第三方巡检问题任务
 *
 * @author jiexiang.sun/Jason
 * @version 1.0.0
 * @create 2022-03-04 0:10
 **/
@RestController
@Validated
@RequestMapping("/wechat/task")
public class WechatTaskController extends BaseController {

    @Autowired
    private IWechatTaskService taskService;


    /**
     * 任务列表查询
     *
     * @param userId
     * @param params
     * @return
     */
    @GetMapping("getList")
    public AjaxResult getList(@RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USERID) Long userId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_ROLEID) Long userRoleId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_DEPTID) Long userDeptId
            , Long startTime, Long endTime
            , FilterForWechatTaskListVO params) {
        params.setUserId(userId);
        params.setUserRoleId(userRoleId);
        params.setUserDeptId(userDeptId);
        if (ObjectUtil.isNotNull(startTime)) {
            params.setStartTime(DateUtil.date(startTime));
        }
        if (ObjectUtil.isNotNull(endTime)) {
            params.setEndTime(DateUtil.date(endTime));
        }

        return AjaxResult.success(taskService.list(params));
    }

    /**
     * 创建任务
     *
     * @param params
     * @param userId
     * @param userRoleId
     * @param userDeptId
     * @return
     */
    @PostMapping("create")
    public AjaxResult create(@Validated @RequestBody CreateForWechatTaskVO params
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USERID) Long userId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_ROLEID) Long userRoleId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_DEPTID) Long userDeptId) {
        params.setCreateUserId(userId);
        params.setCreateUserRoleId(userRoleId);
        params.setCreateUserDeptId(userDeptId);
        WechatTask task = new WechatTask();
        BeanUtils.copyProperties(params, task);
        task.setCreateTime(DateUtil.date());
        return taskService.save(task) ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 删除任务
     *
     * @param taskIds
     * @return
     */
    @DeleteMapping("{taskIds}")
    public AjaxResult remove(@PathVariable String taskIds) {
        if (StrUtil.isBlank(taskIds)) {
            return AjaxResult.success();
        }

        LambdaUpdateWrapper<WechatTask> taskUW = new LambdaUpdateWrapper<>();
        taskUW.in(WechatTask::getId, taskIds.split(","));

        WechatTask task = new WechatTask();
        task.setDelFlag(UserStatus.DELETED.getCode());
        return taskService.update(task, taskUW) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 查看任务详情
     *
     * @param taskId
     * @return
     */
    @GetMapping("info/{taskId}")
    public AjaxResult getList(@PathVariable Long taskId) {
        return AjaxResult.success(taskService.getById(taskId));
    }

    /**
     * 修改任务
     *
     * @param taskId
     * @return
     */
    @PutMapping("{taskId}")
    public AjaxResult remove(@PathVariable Long taskId, @Validated @RequestBody CreateForWechatTaskVO params) {
        LambdaUpdateWrapper<WechatTask> taskUW = new LambdaUpdateWrapper<>();
        taskUW.eq(WechatTask::getId, taskId);

        WechatTask task = new WechatTask();
        BeanUtils.copyProperties(params, task);
        return taskService.update(task, taskUW) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 复制任务
     *
     * @param taskId
     * @return
     */
    @PostMapping("copy/{taskId}")
    public AjaxResult remove(@PathVariable String taskId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USERID) Long userId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_ROLEID) Long userRoleId
            , @RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_DEPTID) Long userDeptId) {

        if (StrUtil.isBlank(taskId)) {
            throw new UserException("wechat.task.copy.id.isblank", null);
        }

        List<WechatTask> list = new ArrayList<>();
        Arrays.stream(taskId.split(",")).forEach(t -> {
            if (StrUtil.isNotBlank(t.trim())) {
                WechatTask task = taskService.getById(t);

                if (ObjectUtil.isNotNull(task)) {
                    task.setId(null);
                    task.setCreateUserId(userId);
                    task.setCreateUserRoleId(userRoleId);
                    task.setCreateUserDeptId(userDeptId);
                    task.setCreateTime(DateUtil.date());
                    list.add(task);
                }
            }
        });
        return taskService.saveBatch(list) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 获取用户部门下所有任务集合
     *
     * @param userDeptId
     * @return
     */
    @GetMapping("allTasks")
    public AjaxResult getAllTask(@RequestAttribute(name = WechatConstants.WECHAT_TOKEN_USER_DEPTID) Long userDeptId) {
        LambdaQueryWrapper<WechatTask> taskQW = new LambdaQueryWrapper<>();
        taskQW.eq(WechatTask::getCreateUserDeptId, userDeptId)
                .eq(WechatTask::getDelFlag, UserStatus.OK.getCode());
        return AjaxResult.success(taskService.list(taskQW));
    }
}
